﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.OneNote;
using System.IO;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace OneNoteFramework.Tests.Hierarchy
{
    public abstract class HierarchyTestBase
    {
        protected virtual string GetRandomName()
        {
            return Path.GetRandomFileName();
        }

        protected virtual string TemporaryFolder
        {
            get { return Path.GetTempPath(); }
        }

        protected OneNoteApplication Application
        {
            get { return OneNoteApplication.Current; }
        }

        protected OneNoteHierarchy Hierarchy
        {
            get { return OneNoteHierarchy.Current; }
        }

        protected void RunNotebookTest(Action<OneNoteNotebook> test)
        {
            OneNoteNotebook notebook = null;
            String notebookPath = Path.Combine(TemporaryFolder, GetRandomName());

            try
            {
                notebook = Hierarchy.OpenNotebook(notebookPath, false);

                Assert.IsNotNull(notebook);
                Assert.AreEqual(notebookPath, notebook.Path);

                test(notebook);
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc);
                throw;
            }
            finally
            {
                if (notebook != null)
                {
                    Hierarchy.CloseNotebook(notebook);
                }
            }
        }

        protected void RunSectionTest(Action<OneNoteSection> test)
        {
            RunNotebookTest(notebook =>
            {
                OneNoteSection section = notebook.OpenSection(GetRandomName());
                
                try
                {
                    test(section);
                }
                finally
                {
                    notebook.Delete(section);
                }
            });
        }

        protected void RunPageTest(Action<OneNotePage> test)
        {
            RunSectionTest(section =>
            {
                OneNotePage page = section.CreatePage();
                try
                {
                    test(page);
                }
                finally
                {
                    section.Delete(page);
                }
            });
        }
    }
}
